package action.PetAction;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import javax.servlet.http.HttpSession;

import model.dao.PetDao;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

import domain.PetInfo;
import Tools.MyTools;

public class showDetailPet extends ActionSupport {
	int pet_Id;

	public int getPet_Id() {
		return pet_Id;
	}

	public void setPet_Id(int petId) {
		pet_Id = petId;
	}

	String pet_Name;

	public String getPet_Name() {
		return pet_Name;
	}

	public void setPet_Name(String petName) {
		pet_Name = petName;
	}

	int state;

	public int getState() {
		return state;
	}

	public void setState(int state) {
		this.state = state;
	}

	public String execute() throws Exception {
		PetDao petdao = new PetDao();
		PetInfo pet = new PetInfo();
		HttpSession session = ServletActionContext.getRequest().getSession();
		ArrayList<PetInfo> pets = (ArrayList<PetInfo>) session
				.getAttribute("pets");
		for (int i = 0; i < pets.size(); i++) {
			if (MyTools.toChinese(pet_Name).equals(pets.get(i).getPet_Name())
					&& pet_Id == pets.get(i).getPet_Id()) {
				pet = pets.get(i);
				break;
			} else {
				continue;
			}
		}
		String realpath = ServletActionContext.getServletContext().getRealPath(
				"/Photo");
		File image = new File(realpath, pet.getPet_PhotoName());
		InputStream is = pet.getPet_Photo();
		if (image != null) {
			File saveFile = new File(new File(realpath), pet.getPet_PhotoName());
			if (!saveFile.getParentFile().exists()) {
				saveFile.getParentFile().mkdirs();
			} else {
				OutputStream os = new FileOutputStream(image);
				byte[] buffer = new byte[1024];
				int length = 0;
				while ((length = is.read(buffer)) > 0) {
					os.write(buffer, 0, length);
				}
			}
		}
		session.setAttribute("petinfo", pet);
		if (state == 1) {
			return "showpet";
		} else if (state == 2) {
			return "editpet";
		} else {
			return "deletepet";
		}
	}

}
